<template>
  <div class="ad">
      <div class="table">
        <!--{{voteName}}-->
          <tr v-if="this.listTitle.length">
             <th class="table-item" v-for="(item, index) of listTitle" :key="index"
             :class="{appear: item === 'cId'}">{{item}}</th>
             <!-- <th class="table-item" v-if="!appear">赞成</th>
             <th class="table-item" v-if="!appear">反对</th>
             <th class="table-item" v-if="!appear">弃权</th>
             <th class="table-item" v-if="appear">分数</th> -->
             <th class="table-item delete">选择</th>
          </tr>
          <tr v-for="(person, index) of listData" :key="index" ref="index">
             <th class="table-item" v-for="(item, key) of person" :key="key" :class="{appear: key === 'cId'}"> {{item}}</th>
             <th class="table-item delete">
                  <input type="checkbox" value="checked"
                  v-model="select[index]"
                  @click="handleSelectClick(index)"
                  :ref="index">
              </th>
          </tr>
      </div>
      <span class="ad-button" @click="handleVoteAgain" v-if="this.listTitle.length">
        选择作为新一轮投票成员
      </span>
      <span class="ad-button" @click="handleSaveVote" v-if="this.listTitle.length">
        结束本轮投票,保存并打印当前结果
      </span>
      <span class="ad-button" @click="handleEndVote" v-if="this.listTitle.length">
        结束这次投票清除所有数据
      </span>
  </div>
</template>

<script>
import axios from 'axios'
import { mapState } from 'Vuex'
export default {
  name: 'HomeList',
  props: {
    listData: Array,
    listTitle: Array,
    vcid: String,
    appear: Boolean
  },
  data () {
    return {
      select: [],
      delete: []
      // voteName: ''
    }
  },
  methods: {
    handleSelectClick (index) {
      this.select[index] = !this.select[index] === true
      if (this.select[index]) {
        this.$refs.index[index].style.background = '#FF4136'
        this.$refs[index][0].checked = true
        // console.log(this.$refs.index[index])
      } else {
        this.$refs.index[index].style.background = '#fff'
        this.$refs[index][0].checked = false
      }
    },
    handleVoteAgain () {
      if (!this.select.length) {
        swal('亲，您还没有选中候选人呢！', '', 'warning')
      } else {
        const verify = confirm('您是否选择这(些)用户再次投票')
        if (verify) {
          this.select.forEach((value, index) => {
            if (value) {
              this.delete.push(this.listData[index])
              // console.log(this.delete)
            }
          })
          const arr = []
          this.delete.forEach((item, index) => {
            arr[index] = item.cId
          })
          // console.log(this.vcid)
          axios.post('http://192.168.43.188:8081/voteAgain', {
            'vcid': this.vcid,
            'arr': arr
          })
            .then(({status, data}) => {
              if (status === 200) { // 这几行代码不能换成三等号
                // console.log(data)
                if (data.msg == '成功初始化第一轮投票') { // eslint-disable-line
                  swal('新一轮投票生成成功', '', 'success')
                  this.changeItem()
                  this.$emit('newVote')
                } else {
                  swal('Info' + data.msg, '', 'error')
                }
              }
            }).catch((error) => {
              swal('问题' + error, '', 'error')
            })
        }
      }
    },
    changeItem () {
      this.delete.forEach(() => { // 保证循环次数
        this.select.forEach((value, index) => {
          if (value) {
            // console.log(this.listData[index])
            // this.listData.splice(index, 1)
            this.select.splice(index, 1)
            this.handleSelectClick(index) // 双重使用恢复正常。
          }
        })
      })
      this.delete = []
    },
    handleSaveVote () {
      axios.post('http://192.168.43.188:8081/excelResults', {
        'vcid': this.vcid,
        'mid': this.userId
      }).then(({data, status}) => {
        if (status === 200) {
          this.handlePrintVote(data.url)
        } else {
          swal(data.msg, '', 'wraning')
        }
      }).catch((error) => {
        swal('Info' + error, '', 'error')
      })
    },
    handlePrintVote (url) {
      // console.log(url)
      const name = url.split('//')
      const fileName = name[name.length - 1]
      // this.voteName = fileName
      for (let i = 0; i < 2; i++) {
        axios({
          method: 'post',
          url: 'http://192.168.43.188:8081/download',
          responseType: 'blob',
          dataType: "jsonp",
          data: {'url': url},
         
        }).then(({data}) => {
          console.log('请求已发送')
          swal('请等待片刻', '', 'info')
          this.download(data, fileName)
          swal('download success', '', 'success')
        })
      } 
    },
    download (data, fileName) {
      if (!data) {
        swal('没有数据', '', 'info')
        return
      }
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      // link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName + '.xls')
      document.body.appendChild(link)
      link.click()
    },
    handleEndVote () {
      swal({
        title: "你确定结束本次投票吗？",
        text: "一旦你决定结束本次投票，将删除所有本次投票的候选人和投票的信息",
        icon: "warning",
        buttons: true,
        dangerMode: true,
      })
      .then((willDelete) => {

        if (willDelete) {
           console.log(this.userPassword,this.userId)
          axios.post('http://192.168.43.188:8081/endVote',{
            'mid': this.userId,
            'pwd': this.userPassword
          }).then(({data} )=> {
            console.log(data)
            //swal(data, {icon: "success"})
            if (data.msg === '111') {
               swal("本次投票结束", '', "success")
            } else {
              swal(data.msg, '', 'error')
            }
          }).catch(error => swal(error, '', 'error'))
        } else {
          swal('您取消了结束本次投票，本次投票依旧继续')
        }
      })
    }
  },
  computed: {
    ...mapState(['themeId']),
    ...mapState(['userId']),
    ...mapState(['userPassword'])
  },
  // mounted () {
  //   swal('投票状态', 'data.msg', "success")
  // }
}
</script>

<style lang="stylus" scoped>
@import '~style/variable.styl'
.ad
    margin-top: .2rem
    text-align: center
    padding: 0 .5rem
    .ad-title
        background: $bgcolor
        color: #fff
        line-height: $height
        text-align: center
        margin-bottom: .5rem
    .ad-button
        color: #fff
        line-height: .45rem
        display: block
        background: $bgcolor
        font-size: .32rem
        padding: .1rem .3rem
        margin: .4rem
        border-radius: .1rem
        width: 21%
        float: left
    .table
        margin-top: .5rem
        width: 100%
        .table-item
            border: .02rem solid #aaa
            width: 4.5rem
            // width: 23.95% /* 设置百分比失效 */
            height: .5rem
            line-height: .5rem
            padding: .2rem .0rem
        .delete
            width: 1rem
        .appear
           display: none
</style>
